// request.js 内容
class request {
  constructor() {
    let token = wx.getStorageSync('token')
    console.log('request', token)
    this._header = {
      'token': token
    }
  }

  /**
   * 设置统一的异常处理
   */
  setErrorHandler(handler) {
    this._errorHandler = handler;
  }

  /**
   * GET类型的网络请求
   */
  getRequest(url, data, header = this._header) {
    header.token = wx.getStorageSync('token')
    return this.requestAll(url, data, header, 'GET')
  }

  /**
   * DELETE类型的网络请求
   */
  deleteRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'DELETE')
  }

  /**
   * PUT类型的网络请求
   */
  putRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'PUT')
  }

  /**
   * POST类型的网络请求
   */
  postRequest(url, data, header = this._header) {
    header.token = wx.getStorageSync('token')
    return this.requestAll(url, data, header, 'POST')
  }

  /**
   * 网络请求
   */
  requestAll(url, data, header, method) {
    header.cookie = wx.getStorageSync("sessionid")
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        data: data,
        header: header,
        method: method,
        success: (res => {
          var cookie = res.header["Set-Cookie"];
          if (cookie != null) {
            wx.setStorageSync("sessionid", res.header["Set-Cookie"]); //服务器返回的 Set-Cookie，保存到本地
          }
          console.log(res)
          if (res.statusCode === 200) {
            if (res.data.code === 10000 || res.data.code === 300) {
              const targetStr = "sys/order/get-order-list";

   


              if (url.indexOf(targetStr) == -1) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'error'
                })
                wx.navigateTo({
                  url: '/pages/index/index',
                })
              }

            } else if (res.data.code === 40000) {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2000 //持续的时间
              })
              return false
            } else if (res.data.code === 9000) {
              console.log('进来啦')
              wx.showToast({
                title: '请勿重复提交！',
                icon: 'none',
                duration: 2000 //持续的时间
              })
              return false
            }
            //200: 服务端业务处理正常结束
            resolve(res)

          } else {
            //其它错误，提示用户错误信息
            if (this._errorHandler != null) {
              //如果有统一的异常处理，就先调用统一异常处理函数对异常进行处理
              this._errorHandler(res)
            }
            reject(res)
          }
        }),
        fail: (res => {
          if (this._errorHandler != null) {
            this._errorHandler(res)
          }
          reject(res)
        })
      })
    })
  }
}

export default request